package zn.io.fastframe.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import zn.io.fastframe.common.utils.R;
import zn.io.fastframe.modules.sys.dao.SysUserTokenDao;
import zn.io.fastframe.modules.sys.entity.SysUserTokenEntity;
import zn.io.fastframe.modules.sys.oAuth2.TokenGenerator;
import zn.io.fastframe.modules.sys.service.SysUserTokenService;

import java.util.Date;

@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity>
        implements SysUserTokenService {

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;


    @Override
    public R createToken(long userId) {
        String token = TokenGenerator.generateValue();
        Date now = new Date();

        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        /**
         * 获取token
         */
        SysUserTokenEntity sysUserTokenEntity = this.baseMapper.selectById(userId);

        if(sysUserTokenEntity == null) {
            sysUserTokenEntity = new SysUserTokenEntity();
            sysUserTokenEntity.setToken(token);
            sysUserTokenEntity.setUserId(userId);
            sysUserTokenEntity.setUpdateTime(now);
            sysUserTokenEntity.setExpireTime(expireTime);
            this.baseMapper.insert(sysUserTokenEntity);
        } else {
            sysUserTokenEntity.setToken(token);
            sysUserTokenEntity.setUpdateTime(now);
            sysUserTokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(sysUserTokenEntity);
        }

        return R.ok().put("token", token).put("expire", EXPIRE);
    }

    @Override
    public void logout(long userId) {

    }
}
